/*
    The MIT License

    Copyright (c) 2010 IFMO/GameDev Studio

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.
*/

#include "fr_local.h"
#include "gl_local.h"

/*-----------------------------------------------------------------------------
	Lighting system :
-----------------------------------------------------------------------------*/

//
//	EFRLightingSystem::EFRLightingSystem
//
EFRLightingSystem::EFRLightingSystem( EFRScene *scene )
{
	this->scene	=	scene;
}


//
//	EFRLightingSystem::~EFRLightingSystem
//
EFRLightingSystem::~EFRLightingSystem( void )
{

}


//
//	EFRLightingSystem::ReloadShader
//
void EFRLightingSystem::ReloadShader( void )
{
	effect	=	scene->fxm->CompileEffect("shaders/lighting.cgfx");
}


//
//	EFRLightingSystem::RenderLighting
//
void EFRLightingSystem::RenderLighting( const EGBuffer &gbuf, IPxTexture color, IPxTexture depth )
{
	uint num = scene->lights.size();
	
	scene->rtm->SetFrameBuffer( depth, color );
	scene->rtm->CopyDepthFrameData( depth, gbuf.ds );
	
	SetupFXUniformsGlobal( gbuf );
	
	RenderAmbient( gbuf );
	
	for (uint i=0; i<num; i++) {	
		EFRLight	*light	=	scene->lights[i].to<EFRLight>();
		
		if (!light) {	
			continue;
		}
		
		if (light->light_type==RS_LIGHT_OMNI) {
			RenderLightOmni( gbuf, color, depth, light );
		} else
		if (light->light_type==RS_LIGHT_SPOT_SHADOW) {
			RenderLightSpotShadow( gbuf, color, depth, light );
		} else
		if (light->light_type==RS_LIGHT_DIRECT_SHADOW) {
			RenderLightDirectShadow( gbuf, color, depth, light );
		}
		
	}
	
	shadow_map = NULL;
}


/*-----------------------------------------------------------------------------
	Light matricies :
-----------------------------------------------------------------------------*/

//
//	EFRLightingSystem::ComputeSMViewProjMatrix
//
EMatrix EFRLightingSystem::ComputeSMViewProjMatrix( const EFRLight *light )
{
	float		radius	=	light->light_radius;
	float		spot	=	light->light_spot;
	float		zfar	=	radius;
	float		znear	=	0.001 * zfar;
	float		width	=	2 * znear / zfar * spot; 
	
	EMatrix	view, proj;

	if ( light->light_type == RS_LIGHT_SPOT_SHADOW ) {	
	
		proj	=	EMatrix::PerspectiveRH( width, width, znear, zfar );
		view	=	ComputeLightViewMatrix( light );
		
	} else if ( light->light_type == RS_LIGHT_DIRECT_SHADOW ) {
	
		proj	=	EMatrix::OrthoRH( spot, spot, -radius, radius );
		view	=	ComputeLightViewMatrix( light );
		
	}
	
	return view * proj;
}


//
//	EFRLightingSystem::ComputeLightWorldMatrix
//
EMatrix EFRLightingSystem::ComputeLightWorldMatrix( const EFRLight *light )
{
	return EMatrix::FromPose( light->light_pos, light->light_orient );
}


//
//	EFRLightingSystem::ComputeLightViewMatrix
//
EMatrix EFRLightingSystem::ComputeLightViewMatrix( const EFRLight *light )
{
	return ComputeLightWorldMatrix( light ).AffineInverse();
}


/*-----------------------------------------------------------------------------
	Light FX setup :
-----------------------------------------------------------------------------*/

//
//	EFRLightingSystem::SetupFXUniformsGlobal
//
void EFRLightingSystem::SetupFXUniformsGlobal( const EGBuffer &gbuf )
{
	if (!effect) { return; }
	
	EMatrix	view		=	scene->view.matrix_view;
	EMatrix	proj		=	scene->proj.matrix_proj;
	EPoint	view_pos	=	scene->view.position;

	EMatrix	vp			=	view * proj;
	EMatrix	vp_i		=	vp.Inverse();
	EMatrix	p_i			=	proj.Inverse();
	EMatrix	ident		=	EMatrix();
	
	uint w, h;
	rs()->GetScreenSize(w, h);

	effect->SetUniform(	"matrix_vp"			,	vp							);
	effect->SetUniform(	"matrix_vp_i" 		,	vp_i						);
	effect->SetUniform(	"matrix_p_i" 		,	p_i							);
	effect->SetUniform(	"rcp_screen_size"	,	EPoint(1.0f/w, 1.0f/h, 0)	);
	effect->SetUniform(	"ambient_level"		,	scene->ambient.color		);
	effect->SetUniform(	"viewer_position"	,	view_pos					);
	
	effect->SetTexture( "sm_gbuffer0"		,	gbuf.clr[0]	);
	effect->SetTexture( "sm_gbuffer1"		,	gbuf.clr[1]	);
	effect->SetTexture( "sm_gbuffer2"		,	gbuf.clr[2]	);
	effect->SetTexture( "sm_depth"			,	gbuf.ds		);
}												


//
//	EFRLightingSystem::SetupFXUniforms
//
void EFRLightingSystem::SetupFXUniforms( const EGBuffer &gbuf, const EFRLight *light )
{
	if (!effect) { return; }

	effect->SetUniform(	"light_color"    	,	light->light_color	);
	effect->SetUniform(	"light_position" 	,	light->light_pos	);
	effect->SetUniform(	"light_radius"   	,	light->light_radius	);

	EMatrix	ident	=	EMatrix();

	if (light->light_type==RS_LIGHT_OMNI) {
		effect->SetUniform(	"matrix_sm_vp"	,	ident	);
		effect->SetUniform(	"matrix_world"	,	ComputeLightWorldMatrix( light )	);
	}

	if (light->light_type==RS_LIGHT_SPOT_SHADOW) {
		effect->SetUniform(	"matrix_sm_vp"		,	ComputeSMViewProjMatrix( light )	);
		effect->SetUniform(	"matrix_world"		,	ComputeLightWorldMatrix( light )	);
		effect->SetTexture( "sm_shadow_map"		,	shadow_map	);
		effect->SetTexture( "sm_shadow_mask"	,	light->light_mask	);
	}
	
	if (light->light_type==RS_LIGHT_DIRECT_SHADOW) {
		effect->SetUniform(	"matrix_sm_vp"		,	ComputeSMViewProjMatrix( light )	);
		effect->SetUniform(	"matrix_world"		,	ComputeLightWorldMatrix( light )	);
		effect->SetTexture( "sm_shadow_map"		,	shadow_map );
		effect->SetTexture( "sm_shadow_mask"	,	light->light_mask	);
		
		effect->SetUniform(	"light_direction"	,	EVector(0,0,1).Rotate( light->light_orient ) );
	}
}


#define SKIP_SETUP
#ifdef SKIP_SETUP

void EFRLightingSystem::EnableStencilMarkingBack( void )	{	}
void EFRLightingSystem::EnableStencilMarkingFront( void )	{	}
void EFRLightingSystem::EnableStencilLightRendering( void )	{	}
void EFRLightingSystem::DisableStencilLighting( void )		{	}

#else

void EFRLightingSystem::EnableStencilMarkingBack( void )
{
	glColorMask	( 0,0,0,0 );
	glDepthMask	( 0 );
	
	glEnable	( GL_CULL_FACE );
	glCullFace	( GL_FRONT );
	glEnable	( GL_DEPTH_TEST );
	
	glEnable	( GL_STENCIL_TEST );
	glStencilMask	( 0x0001 );
	glStencilFunc	( GL_ALWAYS, 0, 0x0001 );	
	glStencilOp		( GL_KEEP, GL_INCR, GL_KEEP );
}

void EFRLightingSystem::EnableStencilMarkingFront( void )
{
	glColorMask	( 0,0,0,0 );
	glDepthMask	( 0 );
	
	glEnable	( GL_CULL_FACE );
	glCullFace	( GL_BACK );
	glEnable	( GL_DEPTH_TEST );
	
	glEnable	( GL_STENCIL_TEST );
	glStencilMask	( 0x0001 );
	glStencilFunc	( GL_ALWAYS, 0, 0x0001 );	
	glStencilOp		( GL_KEEP, GL_DECR, GL_KEEP );
}

void EFRLightingSystem::EnableStencilLightRendering( void )
{
	glColorMask	( 1,1,1,1 );
	glDepthMask	( 1 );
	
	glEnable	( GL_BLEND );
	glBlendFunc	( GL_ONE, GL_ONE );
	
	glDisable	( GL_CULL_FACE );
	glDisable	( GL_DEPTH_TEST );
	
	glEnable	( GL_STENCIL_TEST );
	glStencilMask	( 0x0001 );
	glStencilFunc	( GL_EQUAL, 1, 0x0001 );	
	glStencilOp		( GL_KEEP, GL_KEEP, GL_DECR );
}

void EFRLightingSystem::DisableStencilLighting( void )
{
	glColorMask(1,1,1,1);
	glDepthMask(1);
	glDisable(GL_BLEND);
	glDisable(GL_STENCIL_TEST);
	glDisable(GL_CULL_FACE);
	glDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);
}

#endif





/*-----------------------------------------------------------------------------
	Light rendering :
-----------------------------------------------------------------------------*/

//
//	EFRLightingSystem::RenderLightOmni
//
void EFRLightingSystem::RenderLightOmni( const EGBuffer &gbuf, IPxTexture color, IPxTexture depth, const EFRLight *light )
{
	rs()->GetDVScene()->DrawPoint( light->light_pos, 1, light->light_color );
	
	if (!effect) { return; }

	scene->rtm->SetFrameBuffer( depth, color );
	
	uint n;
	
	effect->SetTechnique("tech_light_omni");
	
	SetupFXUniforms( gbuf, light );
	
	effect->Begin(n);

	for (uint i=0; i<n; i++) {	
		effect->BeginPass(i);

		if (i==0) {		EnableStencilMarkingBack();		}
		if (i==1) {		EnableStencilMarkingFront();	}
		if (i==2) {		EnableStencilLightRendering();	}
		
		DrawShapeOmniLight( light->light_radius );
		
		effect->EndPass();

		DisableStencilLighting();
	}
	
	effect->End();
}


//
//	EFRLightingSystem::RenderLightSpotShadow
//
void EFRLightingSystem::RenderLightSpotShadow( const EGBuffer &gbuf, IPxTexture color, IPxTexture depth, const EFRLight *light )
{
	rs()->GetDVScene()->DrawPoint( light->light_pos, 1, light->light_color );

	if (!effect) { return; }
	
	
	shadow_map	=	scene->rtm->AllocRenderTarget( RS_FORMAT_DEPTH_COMPARABLE, 1024, 1024 );
	
	scene->RenderShadowMap(	shadow_map, EMatrix(), ComputeSMViewProjMatrix( light ) );

	scene->rtm->SetFrameBuffer( depth, color );
	
	uint n;
	
	effect->SetTechnique("tech_light_spot_sm");
	
	SetupFXUniforms( gbuf, light );
	
	effect->Begin(n);

	for (uint i=0; i<n; i++) {	
		effect->BeginPass(i);

		if (i==0) {		EnableStencilMarkingBack();		}
		if (i==1) {		EnableStencilMarkingFront();	}
		if (i==2) {		EnableStencilLightRendering();	}
		
		DrawShapeSpotLight( light->light_radius, light->light_spot );
		
		effect->EndPass();

		DisableStencilLighting();
	}
	
	effect->End();
}


//
//	EFRLightingSystem::RenderLightSpotShadow
//
void EFRLightingSystem::RenderLightDirectShadow( const EGBuffer &gbuf, IPxTexture color, IPxTexture depth, const EFRLight *light )
{
	rs()->GetDVScene()->DrawPoint( light->light_pos, 1, light->light_color );
	
	if (!effect) { return; }

	shadow_map	=	scene->rtm->AllocRenderTarget( RS_FORMAT_DEPTH_COMPARABLE, 1024, 1024 );
	
	scene->RenderShadowMap(	shadow_map, EMatrix(), ComputeSMViewProjMatrix( light ) );

	scene->rtm->SetFrameBuffer( depth, color );
	
	uint n;
	
	effect->SetTechnique("tech_light_direct_sm");
	
	SetupFXUniforms( gbuf, light );
	
	effect->Begin(n);

	for (uint i=0; i<n; i++) {	
		effect->BeginPass(i);

		if (i==0) {		EnableStencilMarkingBack();		}
		if (i==1) {		EnableStencilMarkingFront();	}
		if (i==2) {		EnableStencilLightRendering();	}
		
		DrawShapeDirectLight( light->light_radius, light->light_spot );
		
		effect->EndPass();

		DisableStencilLighting();
	}
	
	effect->End();
}


/*-----------------------------------------------------------------------------
	Light shapes :
-----------------------------------------------------------------------------*/

//
//	EFRLightingSystem::DrawShapeCube
//
void EFRLightingSystem::DrawShapeCube( float szx, float szy, float szz )
{
#if 0
	EPoint	p0	=	EPoint(  szx,  szy,  szz );
	EPoint	p1	=	EPoint( -szx,  szy,  szz );
	EPoint	p2	=	EPoint( -szx, -szy,  szz );
	EPoint	p3	=	EPoint(  szx, -szy,  szz );
	EPoint	p4	=	EPoint(  szx,  szy, -szz );
	EPoint	p5	=	EPoint( -szx,  szy, -szz );
	EPoint	p6	=	EPoint( -szx, -szy, -szz );
	EPoint	p7	=	EPoint(  szx, -szy, -szz );


	glBegin( GL_QUADS );
	
		/* Z+ */	
		glVertex4fv ( p0.v );		glVertex4fv ( p1.v );	
		glVertex4fv ( p2.v );		glVertex4fv ( p3.v );
		
		/* Z- */	
		glVertex4fv ( p7.v );		glVertex4fv ( p6.v );	
		glVertex4fv ( p5.v );		glVertex4fv ( p4.v );

		/* Y+ */	
		glVertex4fv ( p0.v );		glVertex4fv ( p4.v );	
		glVertex4fv ( p5.v );		glVertex4fv ( p1.v );
		
		/* Y- */	
		glVertex4fv ( p7.v );		glVertex4fv ( p3.v );	
		glVertex4fv ( p2.v );		glVertex4fv ( p6.v );

		/* X+ */	
		glVertex4fv ( p0.v );		glVertex4fv ( p3.v );	
		glVertex4fv ( p7.v );		glVertex4fv ( p4.v );
		
		/* X- */	
		glVertex4fv ( p1.v );		glVertex4fv ( p5.v );	
		glVertex4fv ( p6.v );		glVertex4fv ( p2.v );
	
	glEnd();
#else
	GLfloat vertices_val[] = {	szx,  szy,  szz, 
							   -szx,  szy,  szz, 
							   -szx, -szy,  szz, 
								szx, -szy,  szz, 
								szx,  szy, -szz, 
							   -szx,  szy, -szz, 
							   -szx, -szy, -szz, 
								szx, -szy, -szz  };

	GLubyte indices[] = { 0,1,2,3, 7,6,5,4, 0,4,5,1, 7,3,2,6, 0,3,7,4, 1,5,6,2 };

	std::vector<GLfloat> vertices(24*3);

	for(uint i=0, j=0; i<24; i++, j+=3) {
		vertices[j]		= vertices_val[ indices[i]*3 ];
		vertices[j + 1] = vertices_val[ indices[i]*3 + 1];
		vertices[j + 2] = vertices_val[ indices[i]*3 + 2];
	}


	GL_CALL( glEnableClientState(GL_VERTEX_ARRAY) );
	GL_CALL( glVertexPointer(3, GL_FLOAT, 0, &vertices.front()) );

	GL_CALL( glDrawArrays(GL_QUADS, 0, 24) );

	// deactivate vertex arrays after drawing
	GL_CALL( glDisableClientState(GL_VERTEX_ARRAY) );

	vertices.clear();

#endif
}


//
//	EFRLightingSystem::DrawShapeOmniLight
//
void EFRLightingSystem::DrawShapeOmniLight( float radius )
{
	DrawShapeCube( radius, radius, radius );
}


//
//	EFRLightingSystem::DrawShapeDirectLight
//
void EFRLightingSystem::DrawShapeDirectLight( float depth, float size )
{
	DrawShapeCube( size, size, depth );
}

//
//	EFRLightingSystem::DrawShapeSpotLight
//
void EFRLightingSystem::DrawShapeSpotLight( float radius, float spot )
{
#if 0
	float	s	=	spot;
	float	r	=	radius;
	EPoint	p0	=	EPoint(	 0,	 0,	 0 );
	EPoint	p1	=	EPoint(  s,  s, -r );
	EPoint	p2	=	EPoint(  s, -s, -r );
	EPoint	p3	=	EPoint( -s, -s, -r );
	EPoint	p4	=	EPoint( -s,  s, -r );

	glBegin( GL_QUADS );
		glVertex4fv ( p1.v );
		glVertex4fv ( p2.v );
		glVertex4fv ( p3.v );
		glVertex4fv ( p4.v );
	glEnd();

	glBegin( GL_TRIANGLES );
		glVertex4fv ( p1.v );	glVertex4fv ( p0.v );	glVertex4fv ( p2.v );
		glVertex4fv ( p2.v );	glVertex4fv ( p0.v );	glVertex4fv ( p3.v );
		glVertex4fv ( p3.v );	glVertex4fv ( p0.v );	glVertex4fv ( p4.v );
		glVertex4fv ( p4.v );	glVertex4fv ( p0.v );	glVertex4fv ( p1.v );
	glEnd();
#else
	float	s	=	spot;
	float	r	=	radius;

	std::vector<GLfloat> vertices(12*3);

	GLfloat points[] = {  0,  0,  0,
						  s,  s, -r,
						  s, -s, -r,
						 -s, -s, -r,
						 -s,  s, -r  };

	GLubyte indices[] = { 1,0,2, 2,0,3, 3,0,4, 4,0,1 };

	for(uint i=0, j=0; i<12; i++, j+=3) {
		vertices[j]		= points[ indices[i]*3 ];
		vertices[j + 1] = points[ indices[i]*3 + 1];
		vertices[j + 2] = points[ indices[i]*3 + 2];
	}

	GL_CALL( glEnableClientState(GL_VERTEX_ARRAY)		 );
	GL_CALL( glVertexPointer(3, GL_FLOAT, 0, points + 3) );

	GL_CALL( glDrawArrays(GL_QUADS, 0, 4) );

	GL_CALL( glVertexPointer(3, GL_FLOAT, 0, &vertices.front()) );

	GL_CALL( glDrawArrays(GL_TRIANGLES, 0, 12) );

	GL_CALL( glDisableClientState(GL_VERTEX_ARRAY) );

	vertices.clear();

#endif
}


/*-----------------------------------------------------------------------------
	Ambient lighting :
-----------------------------------------------------------------------------*/

//
//	EFRLightingSystem::RenderAmbient
//
void EFRLightingSystem::RenderAmbient( const EGBuffer &gbuf )
{
	if (!effect) {
		return;
	}

	effect->SetTechnique("tech_ambient");

	uint n;
	effect->Begin(n);

	for (uint i=0; i<n; i++) {	
		effect->BeginPass(i);

		scene->vbm->DrawFSQuad();
		
		effect->EndPass();
	}
	
	effect->End();	
	
}
